package com.qk.management.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.PageResult;
import com.qk.common.util.JwtUtils;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDto;
import com.qk.management.mapper.RoleMapper;
import com.qk.vo.LoginResultVo;
import com.qk.entity.User;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    private static final String DEFAULT_PASSWORD_SUFFIX = "123";
    private static final Integer LOGIN_STATUS_SUCCESS = 1;

    @Override
    public List<User> getUserListByDeptId(Integer deptId) {
        return userMapper.selectUserListByDeptId(deptId);
    }

    @Override
    public List<User> getUserListByRoleLabel(String roleLabel) {
        return userMapper.selectUserListByRoleLabel(roleLabel);
    }

    @Override
    public List<User> getUserList() {
        return userMapper.selectUserList();
    }


    @Override
    public PageResult<UserDO> getUsers(UserDTO userDto) {
        PageHelper.startPage(userDto.getPage(), userDto.getPageSize());
        List<UserDO> users = userMapper.getUsers(userDto);
        users.forEach(user -> {
            user.setPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
        });
        Page<UserDO> pageInfo = (Page<UserDO>) users;
        return PageResult.<UserDO>builder()
                .total(pageInfo.getTotal())
                .rows(pageInfo.getResult())
                .build();
    }

    @Override
    public void addUser(User user) {
        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "deptId", "roleId","image", "remark", "createTime", "updateTime");
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        String rawPassword = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFFIX).toString();
        user.setPassword(DigestUtils.md5DigestAsHex(rawPassword.getBytes()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
    }

    @Override
    public void deleteUsers(List<Integer> ids) {
        userMapper.deleteByIds(ids);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public void updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public LoginResultVo login(UserLoginDto userLoginDto) {
        boolean hasNull = BeanUtil.hasNullField(userLoginDto, "username", "password");
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 查询用户信息
        User user = userMapper.selectUserByUsername(userLoginDto.getUsername());
        if (Objects.isNull(user)) {
            CommonException.throwCommonException(ParamEnum.USER_NOT_FOUND);
        }
        // 校验密码
        if (!Objects.equals(user.getPassword(), DigestUtils.md5DigestAsHex(userLoginDto.getPassword().getBytes()))) {
            CommonException.throwCommonException(ParamEnum.PASSWORD_ERROR);
        }

        // 校验用户状态
        if (!Objects.equals(user.getStatus(), LOGIN_STATUS_SUCCESS)) { // 0 表示停用状态
            CommonException.throwCommonException(ParamEnum.USER_DISABLED);
        }

        String roleLabel = roleMapper.selectByUserId(user.getRoleId());
        HashMap<String, Object> clamins = new HashMap<>();
        clamins.put("userid", user.getId());
        clamins.put("username", user.getUsername());

        return LoginResultVo.builder()
                .id(user.getId())
                .username(user.getUsername())
                .name(user.getName())
                .image(user.getImage())
                .roleLabel(roleLabel)
                .token(JwtUtils.generateToken(clamins))
                .build();
    }
}